<?php
/**
 * Created by PhpStorm.
 * User: lizhenhua
 * Date: 2018/3/7
 * Time: 10:20
 */

namespace App\Http\Controllers\Admin;

use App\Http\Requests\AddUserPost;
use App\Http\Requests\UpdateUserPost;
use App\Models\Autonym;
use App\Models\Currency;
use App\Models\Message;
use App\Models\MessageTpl;
use App\Models\Property;
use App\Models\PropertyInfo;
use App\Models\Slide;
use App\Models\User;
use Dotenv\Validator;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use OSS\OssClient;
use App\Library\Yunxin;
use App\Traits\YunXinTrait;

class UserController extends Controller
{
    use YunXinTrait;

    public function __construct()
    {
        view()->share('menu', 'user');
    }

    /**
     * 会员列表
     * @pltaram  Request $request [description]
     * @return [type]           [description]
     */
    public function index(Request $request)
    {
//        dd($request->post());
        $account = $request->post('like_account');
        $nickname = $request->post('like_nickname');
        $email = $request->post('like_email');
        //筛选条件
        /*if ($account && empty($nickname)) {
            $result = User::where('type', '=', 1)
            ->where('account', 'like', '%' . $account . '%')
            ->orderBy('created_at', 'desc')
            ->paginate(8);
        } elseif (empty($account) && $nickname) {
            $result = User::where('type', '=', 1)
            ->where('nickname', 'like', '%' . $nickname . '%')
            ->orderBy('created_at', 'desc')->paginate(8);
        } elseif ($account && $nickname) {
            $result = User::where('type', '=', 1)
            ->where('nickname', 'like', '%' . $nickname . '%')
            ->where('account', 'like', '%' . $account . '%')
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        } else {
            $result = User::where('type', '=', 1)
            ->orderBy('created_at', 'desc')
            ->paginate(8);
        }*/

        $result = User::where('type', 1)
            ->where(function ($query) use ($account) {
                if (!empty($account)) {
                    $query->where('account', 'like', '%' . $account . '%');
                }
            })
            ->where(function ($query) use ($nickname) {
                if (!empty($nickname)) {
                    $query->where('nickname', 'like', '%' . $nickname . '%');
                }
            })
            ->where(function ($query) use ($email) {
                if (!empty($email)) {
                    if (isEmail($email)) {
                        $query->where(['email' => $email]);
                    } elseif (isPhone($email)) {
                        $query->where(['phone' => $email]);
                    }
                }
            })
            ->orderBy('created_at', 'desc')
            ->paginate(8);

        $tid = Currency::where(['name_en' => 'OBA'])->value('id');
        $uid = Currency::where(['name_en' => 'USDT'])->value('id');
        $data = [];
        foreach ($result as $key => $val) {
            $data[$key]['account'] = $val->account;
            $data[$key]['id'] = $val->id;
            $data[$key]['nickname'] = $val->nickname;
            $data[$key]['real_status'] = $val->real_status;
            $data[$key]['status'] = $val->status;
            $data[$key]['email'] = $val->email;
            $data[$key]['phone'] = $val->phone;
            $data[$key]['balance_tlb'] = Property::where(['uid' => $val->id, 'cid' => $tid])->value('balance') ?? "未添加该资产" ;
            $data[$key]['blocked_tlb'] = Property::where(['uid' => $val->id, 'cid' => $tid])->value('blocked') ?? "未添加该资产";
            $data[$key]['balance_btb'] = Property::where(['uid' => $val->id, 'cid' => $uid])->value('balance') ?? "未添加该资产";
            $data[$key]['blocked_btb'] = Property::where(['uid' => $val->id, 'cid' => $uid])->value('blocked') ?? "未添加该资产";
            $data[$key]['time'] = $val->created_at;
            $data[$key]['account'] = $val->account;
        }
        //dd($data);
        $url = ['like_account' => $account, 'like_nickname' => $nickname];
        return view('admin/user/index', compact('data', 'result', 'account', 'nickname', 'url', 'email'));
    }


    /**
     * 添加会员
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function add_user(Request $request)
    {
//        dd(1);
        return view('admin/user/add_user');
    }

    public function editor_user(AddUserPost $request)
    {
        $request->validate([
            'password' => 'required|min:6|max:20|regex:/^[a-zA-Z0-9]{6,20}$/',
            'account' => 'required',
            'pay_pass' => 'required|min:6|max:10|regex:/^[a-zA-Z0-9]{6,16}$/'
        ]);
        $account = $request->post('account');
        $password = $request->post('password');
        $real_password = $request->post('real_password');
        $pay_pass = $request->post('pay_pass');
        $rea_pay_pass = $request->post('re_pay_pass');

        if (empty($password) || empty($real_password) || empty($pay_pass) || empty($rea_pay_pass) || empty($account)) {
            return back()->with(['msg' => '请填写完整的数据', 'status' => 0]);
        }
        if ($pay_pass != $rea_pay_pass) {
            return back()->with(['msg' => '两次交易密码不相同', 'status' => 0]);
        }
        if ($password != $real_password) {
            return back()->with(['msg' => '两次登录密码不相同', 'status' => 0]);
        }
        if ($password == $pay_pass) {
            return back()->with(['msg' => '登录密码不能和支付密码相同', 'status' => 0]);
        }
        $email = $phone = $user = $check = null;
        if (isPhone($account)) {
            $phone = $account;
            $user = User::where(['phone' => $phone])->first();
        } elseif (isEmail($account)) {
            $email = $account;
            $user = User::where(['email' => $email])->first();
        } else {
            return back()->with(['msg' => '账号格式不正确', 'status' => 0]);
        }
        if ($user) {
            return back()->with(['msg' => '账号已注册', 'status' => 0]);
        }
        $img = randomHeadimg();
        $date = [
            'phone' => $phone,
            'nickname' => getNickname(),
            'account' => getAccount(),
            'email' => $email,
            'password' => md5($password),
            'pay_pass' => md5($pay_pass),
            'headimg' => $img,
            'real_status' => 1,
        ];
//          dd($date);
//          $result1 = User::where('id',1)->first();
//          dd($result1);
        $result = User::create($date);
        $id = $result->id;
        $cid = Currency::where(['online_switch' => 1])->get();
        $model = new Yunxin\Yunxin();
        $name = $date['nickname'];
        $arr = $model->register_yx($id, $name, $img);
        if ($arr['status'] = 1) {
            $yx_check = User::where('id', $id)->update(['yx_status' => 2]);
        }
        //资产表数据
        $c_USDT = Currency::where(['name_en'=>'USDT'])->value('id');
//        foreach ($cid as $k => $value) {
            $info = [
                'uid' => $id,
                'cid' => $c_USDT,
                'balance' => 0,
                'blocked' => 0,
                'total' => 0,
            ];
            Property::create($info);
//        }
        if ($result) {
            return back()->with(['msg' => '添加成功', 'status' => 1, 'msg_url' => 'user_list']);
        } else {
            return back()->with(['msg' => '添加失败', 'status' => 1, 'msg_url' => 'user_list']);
        }
    }

    /**
     * 财务日志
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function finance_list(Request $request)
    {
        $uid = $request->post('id');
        $cid = $request->post('cid');


        $user_name = User::where('id', '=', $uid)->value('account');
        if (empty($cid)) {
            $result = PropertyInfo::where(['uid' => $uid])->orderBy('created_at', 'DESC')->paginate(10);
        } else {
            $result = PropertyInfo::where(['uid' => $uid, 'cid' => $cid])->orderBy('created_at', 'DESC')->paginate(10);
        }
//        dd($request);
        $price = Currency::get();
        $data = [];
        foreach ($result as $k => $value) {
            $data[$k]['name'] = Currency::where(['id' => $value->cid])->value('name_en');
            $data[$k]['note'] = $value->note;
            if ($value->deal_type == 2) {
                $data[$k]['price'] = $value->proc;
            } else {
                $data[$k]['price'] = $value->price;
            }
            $data[$k]['num'] = $value->num;
            $data[$k]['total'] = $value->total;
            $data[$k]['time'] = $value->created_at;
            $data[$k]['status'] = $value->status;
        }
        $url = ['cid' => $cid, 'id' => $uid];
        return view('admin/user/finance_list', compact('user_name', 'data', 'price', 'uid', 'url', 'result'));
    }

    /**
     * 个人信息
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function user_info(Request $request)
    {
        $uid = $request->post('id');
        $user_name = User::where('id', '=', $uid)->first();
        $real_name = Autonym::where('uid', '=', $uid)->first();
        $property = Property::where('uid', '=', $uid)->get();
        $data = [];
        foreach ($property as $k => $value) {
            $data[$k]['balance'] = $value['balance'] ?? 0;
            $data[$k]['blocked'] = $value['blocked'] ?? 0;
            $data[$k]['name_en'] = Currency::where('id', '=', $value['cid'])->value('name_en');
        }
        if ($real_name){
            $real_name['front_card'] = config('alioss.host') . '/' . $real_name['front_card'];
            $real_name['back_card'] = config('alioss.host') . '/' . $real_name['back_card'];
            $real_name['hand_card'] = config('alioss.host') . '/' . $real_name['hand_card'];
        }
        $user_name['headimg'] = config('alioss.host') . '/' . $user_name['headimg'];
//        dd($data);
        return view('admin/user/user_info', compact('user_name', 'data', 'real_name'));
    }

    /**
     * 个人信息修改
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function update_user(Request $request)
    {
        $data = [];
//        dd($request->has('logo'));
        $data['nickname'] = $request->post('nickname');
        $account = $request->post('account');

        $id = $request->post('id');
        if (empty($data['nickname']) || empty($account)) {
            return back()->with(['msg' => '请填写完整的数据', 'status' => 0]);
        }
        $data['email'] = $data['phone'] = $user = $check = null;
        if (isPhone($account)) {
            $data['phone'] = $account;
        } elseif (isEmail($account)) {
            $data['email'] = $account;
        } else {
            return back()->with(['msg' => '账号格式不正确', 'status' => 0]);
        }
        if (!empty($request->post('password'))) {
            $a = isPassword($request->post('password'));
            if ($a == false){
                return back()->with(['msg' => '登录密码为数字或字母', 'status' => 0]);
            }
            if (strlen($request->post('password')) < 6 || strlen($request->post('password')) > 20) {
                return back()->with(['msg' => '登录密码长度为6到20之间', 'status' => 0]);
            }
            $data['password'] = md5($request->post('password'));
        }
        if (!empty($request->post('pay_pass'))) {
            $a = isPassword($request->post('pay_pass'));
            if ($a == false){
                return back()->with(['msg' => '交易密码为数字或字母', 'status' => 0]);
            }
            if (strlen($request->post('pay_pass')) < 6 || strlen($request->post('pay_pass')) > 10) {
                return back()->with(['msg' => '交易密码长度为6到10之间', 'status' => 0]);
            }
            $data['pay_pass'] = md5($request->post('pay_pass'));
        }
//        dd($data);
        $oss = new OssClient(config('alioss.accessKeyId'), config('alioss.accessKeySecret'), config('alioss.endpoint'));
        $logo = '';
        if ($request->has('logo')) {
            $logo = $request->file('logo');
            if ($logo) {
                if ($logo->isValid()) {
                    $realPath = $logo->getRealPath(); //临时文件的绝对路径
                    $ext = $logo->getClientOriginalExtension(); // 扩展名
                    $filename = date('YmdHis') . '_' . uniqid() . '.' . $ext; //文件名
                    $osspath = 'block_chain/' . $filename; //oss路径
                    $oss->uploadFile(config('alioss.bucket'), $osspath, $realPath); //上传文件到阿里云
                    $data['headimg'] =  $osspath; //数据库保存全路径文件名
                }
            }
        }
        /*$img = User::where('id', $id)->value('headimg');
        if (!empty($data['headimg'])) {
            $img = config('alioss.host') . '/' .$data['headimg'];
        }
        $model = new Yunxin\Yunxin();
        $arr = $model->change_yx($id, $data['nickname'], $img,'');*/
        $result = User::updateOrCreate(
            [
                'id' => $id,
            ],
            $data
        );
        if ($result) {
            return back()->with(['msg' => '添加成功', 'status' => 1, 'msg_url' => 'user_list']);
        }
    }

    /**
     * 实名认证
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function check_user_info(Request $request)
    {
        $id = $request->get('id');
        $data = Autonym::where('uid', $id)->first();
        if ($data){
            $data['front_card'] = config('alioss.host') . '/' . $data['front_card'];
            $data['back_card'] = config('alioss.host') . '/' . $data['back_card'];
            $data['hand_card'] = config('alioss.host') . '/' . $data['hand_card'];
        }
        return view('admin/user/check_user', compact('id', 'data'));
    }

    public function check_user(Request $request)
    {
        $data = [];
        //dd($request->post());
        $data['name'] = $request->post('name');
        $data['indentity_card'] = $request->post('user_card');
        $k_time = $request->post('k_time');
        $e_time = $request->post('e_time');
        if (empty($e_time)||empty($k_time)||empty($data['name'])||empty($data['indentity_card'])){
            return back()->with(['msg' => '请填写完整的数据', 'status' => 0]);
        }
        if ($k_time>$e_time){
            return back()->with(['msg' => '身份办理时间应小于失效时间', 'status' => 0]);
        }
        $data['time'] = $k_time.'-'.$e_time;
        $uid = $request->post('uid');
        $card_one = isIdentity($data['indentity_card']);
        $card_two = $data['indentity_card'];
        if ($card_one == false && $card_two == false) {
            return back()->with(['msg' => '身份证格式不正确', 'status' => 0]);
        }
        $oss = new OssClient(config('alioss.accessKeyId'), config('alioss.accessKeySecret'), config('alioss.endpoint'));
        if ($request->has('front_photo')) {
            $logo = $request->file('front_photo');
            if ($logo) {
                if ($logo->isValid()) {
                    $realPath = $logo->getRealPath(); //临时文件的绝对路径
                    $ext = $logo->getClientOriginalExtension(); // 扩展名
                    $filename = date('YmdHis') . '_' . uniqid() . '.' . $ext; //文件名
                    $osspath = 'block_chain/' . $filename; //oss路径
                    $oss->uploadFile(config('alioss.bucket'), $osspath, $realPath); //上传文件到阿里云
                    $data['front_card'] =  $osspath; //数据库保存全路径文件名
                }
            }
        } else {
            return back()->with(['msg' => '请上传身份证正面照片', 'status' => 0]);
        }
        if ($request->has('back_photo')) {
            $logo = $request->file('back_photo');
            if ($logo) {
                if ($logo->isValid()) {
                    $realPath = $logo->getRealPath(); //临时文件的绝对路径
                    $ext = $logo->getClientOriginalExtension(); // 扩展名
                    $filename = date('YmdHis') . '_' . uniqid() . '.' . $ext; //文件名
                    $osspath = 'block_chain/' . $filename; //oss路径
                    $oss->uploadFile(config('alioss.bucket'), $osspath, $realPath); //上传文件到阿里云
                    $data['back_card'] =  $osspath; //数据库保存全路径文件名
                }
            }
        } else {
            return back()->with(['msg' => '请上传身份证背面照片', 'status' => 0]);
        }
        if ($request->has('hand_card')) {
            $logo = $request->file('hand_card');
            if ($logo) {
                if ($logo->isValid()) {
                    $realPath = $logo->getRealPath(); //临时文件的绝对路径
                    $ext = $logo->getClientOriginalExtension(); // 扩展名
                    $filename = date('YmdHis') . '_' . uniqid() . '.' . $ext; //文件名
                    $osspath = 'block_chain/' . $filename; //oss路径
                    $oss->uploadFile(config('alioss.bucket'), $osspath, $realPath); //上传文件到阿里云
                    $data['hand_card'] =  $osspath; //数据库保存全路径文件名
                }
            }
        } else {
            return back()->with(['msg' => '请上传身份证背面照片', 'status' => 0]);
        }
        $user_check = User::where('id', $uid)->update(['real_status' => 3]);
        Autonym::where('uid', $uid)->update(['status' => 1]);
        $msg = ['msg_id' => 15, 'uid' => $uid];
        (new Message())->syspublishsmsAll($msg);
        $result = Autonym::updateOrCreate(
            [
                'uid' => $uid,
            ],
            $data
        );
        if ($result && $user_check) {
            return back()->with(['msg' => '添加成功', 'status' => 1, 'msg_url' => 'audit_user']);
        }
    }



    /**
     * 审核列表
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function audit_user(Request $request)
    {
        $like_account = '';
        if ($request->post('like_account')) {
            $like_account = $request->post('like_account');
        }
        //联查获取未审核人
        $result = Autonym::whereHas('users', function ($q) use ($like_account) {
            $q->where('account', 'like', '%' . $like_account . '%');
        })->where('status', '=', '1')->orderBy('created_at', 'desc')->paginate(15);

        $data = [];
        foreach ($result as $k => $value) {
            $data[$k] = User::where('id', '=', $value->uid)->first();
            $data[$k]['create_time'] = $value->created_at;
            $data[$k]['user_status'] = $value->status;
        }
        $url = ['account' => $like_account];
//        dd($data);
        return view('admin/user/audit_user', compact('data', 'result', 'like_account', 'url'));
    }

    /**
     * 审核信息
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function audit_info(Request $request)
    {
        $id = $request->get('id');
        $type = $request->get('type');
        $uid = $request->get('uid');
        $data = Autonym::where('uid', '=', $id)->first();
        $data['front_card'] = config('alioss.host') . '/' . $data['front_card'];
        $data['back_card'] = config('alioss.host') . '/' . $data['back_card'];
        $data['hand_card'] = config('alioss.host') . '/' . $data['hand_card'];

//        dd($data);
        return view('admin/user/audit_info', compact('data', 'id'));
    }
    /**
     * 审核判断
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function check_audit_info(Request $request){
        $type = $request->get('type');
        $uid = $request->get('uid');
            if (empty($type)){
                return back()->with(['msg' => '审核状态必须勾选', 'status' => 0]);
            }
            if ($type == 1) {
                $result = Autonym::where('uid', '=', $uid)->update(['status' => 2]);
                $real = User::where('id', '=', $uid)->update(['real_status' => 2]);
                $msg = ['msg_id' => 16, 'uid' => $uid];
                (new Message())->syspublishsmsAll($msg);
                if ($result && $real) {
                    return back()->with(['msg' => '提交成功', 'status' => 1, 'msg_url' => 'audit_user']);
                }
            } else {
                $note = $request->get('note');
                if (empty($note))
                    return back()->with(['msg' => '审核不通过必须填写原因', 'status' => 0]);
                if(strlen($note)>90)
                    return back()->with(['msg' => '审核原因不得超过三十字', 'status' => 0]);
                $result = Autonym::where('uid', '=', $uid)->update(['status' => 3, 'note' => $note]);
                $real = User::where('id', '=', $uid)->update(['real_status' => 4]);
                $msg = ['msg_id' => 17, 'uid' => $uid,'message' => [$note]];
                (new Message())->syspublishsmsAll($msg);
                if ($result && $real) {
                    return back()->with(['msg' => '提交成功', 'status' => 1, 'msg_url' => 'audit_user']);
                }
            }
    }

}
